const app = getApp();
const { mockData } = require('../../utils/mock-data');
const { request } = require('../../utils/request');

Page({
  data: {
    // 登录状态
    isLoggedIn: false,
    // 登录表单
    loginForm: {
      username: '',
      password: ''
    },
    showLoginModal: false,
    // 注册表单
    registerForm: {
      username: '',
      password: '',
      confirmPassword: ''
    },
    showRegisterModal: false,
    // 用户信息
    userInfo: {
      nickname: '',
      bio: '',
      avatar: '',
      stats: { favorites: 0, plays: 0, following: 0 }
    },
    
    // 播放历史
    playHistory: [],
    
    // 收藏列表
    favorites: [],
    
    // 推荐歌单
    recommendedPlaylists: [],
    
    // 本地音乐列表
    localMusic: [],
    
    // 设置选项
    qualityOptions: ['标准音质', '高品质', '无损音质'],
    qualityIndex: 0,
    autoPlay: true,
    
    // 编辑资料
    editProfile: {
      nickname: '',
      bio: '',
      avatar: ''
    },
    
    // 弹窗状态
    showFavoritesModal: false,
    showLocalMusicModal: false,
    showSettingsModal: false,
    showEditProfileModal: false
  },

  onLoad() {
    // 检查登录状态
    const isLoggedIn = wx.getStorageSync('isLoggedIn') || false;
    this.setData({ isLoggedIn });
    
    if (isLoggedIn) {
      this.initData();
    }
  },

  onShow() {
    // 检查登录状态
    const isLoggedIn = wx.getStorageSync('isLoggedIn') || false;
    this.setData({ isLoggedIn });
    
    if (isLoggedIn) {
      // 更新数据
      this.updateData();
    }
  },

  // 显示登录弹窗
  showLogin() {
    this.setData({
      showLoginModal: true,
      loginForm: {
        username: '',
        password: ''
      }
    });
  },

  // 关闭登录弹窗
  closeLoginModal() {
    this.setData({ showLoginModal: false });
  },

  // 用户名输入
  onUsernameChange(e) {
    this.setData({
      'loginForm.username': e.detail.value
    });
  },

  // 密码输入
  onPasswordChange(e) {
    this.setData({
      'loginForm.password': e.detail.value
    });
  },

  // 显示注册弹窗
  showRegister() {
    this.setData({
      showLoginModal: false,
      showRegisterModal: true,
      registerForm: {
        username: '',
        password: '',
        confirmPassword: ''
      }
    });
  },

  // 关闭注册弹窗
  closeRegisterModal() {
    this.setData({ showRegisterModal: false });
  },

  // 注册用户名输入
  onRegUsernameChange(e) {
    this.setData({
      'registerForm.username': e.detail.value
    });
  },

  // 注册密码输入
  onRegPasswordChange(e) {
    this.setData({
      'registerForm.password': e.detail.value
    });
  },

  // 注册确认密码输入
  onRegConfirmChange(e) {
    this.setData({
      'registerForm.confirmPassword': e.detail.value
    });
  },

  // 提交注册（调用后端）
  async submitRegister() {
    const { username, password, confirmPassword } = this.data.registerForm;
    if (!username || !password || !confirmPassword) {
      wx.showToast({ title: '请填写完整信息', icon: 'none' });
      return;
    }
    if (password !== confirmPassword) {
      wx.showToast({ title: '两次密码输入不一致', icon: 'none' });
      return;
    }

    try {
      await request('/api/register', 'POST', { username, password });
      wx.showToast({ title: '注册成功', icon: 'success' });
      this.setData({
        showRegisterModal: false,
        showLoginModal: true,
        'loginForm.username': username,
        'loginForm.password': ''
      });
    } catch (err) {
      wx.showToast({ title: err || '注册失败', icon: 'none' });
    }
  },

  // 提交登录（调用后端）
  async submitLogin() {
    const { username, password } = this.data.loginForm;
    if (!username || !password) {
      wx.showToast({ title: '请输入账号和密码', icon: 'none' });
      return;
    }

    try {
      const res = await request('/api/login', 'POST', { username, password });
      wx.setStorageSync('token', res.token);
      wx.setStorageSync('isLoggedIn', true);
      this.setData({
        isLoggedIn: true,
        showLoginModal: false,
        'userInfo.nickname': res.userInfo.username
      });
      this.initData();
      wx.showToast({ title: '登录成功', icon: 'success' });
    } catch (err) {
      wx.showToast({ title: err || '登录失败', icon: 'none' });
    }
  },

  // 登出方法
  handleLogout() {
    wx.setStorageSync('isLoggedIn', false);
    this.setData({ 
      isLoggedIn: false,
      userInfo: {
        nickname: '',
        bio: '',
        avatar: '',
        stats: { favorites: 0, plays: 0, following: 0 }
      }
    });
    
    wx.showToast({
      title: '已退出登录',
      icon: 'success'
    });
  },

  initData() {
    // 从本地存储加载真实数据
    const userInfo = mockData.userInfo;
    const playHistory = app.getHistory();
    const favorites = app.getFavorites();
    
    // 初始化推荐歌单数据
    const recommendedPlaylists = [
      {
        id: 1,
        name: '热门推荐',
        cover: 'https://picsum.photos/300/300?random=1',
        songCount: 20,
        description: '最新热门歌曲合集'
      },
      {
        id: 2,
        name: '私人雷达',
        cover: 'https://picsum.photos/300/300?random=2',
        songCount: 30,
        description: '根据您的喜好推荐'
      },
      {
        id: 3,
        name: '经典老歌',
        cover: 'https://picsum.photos/300/300?random=3',
        songCount: 25,
        description: '怀旧经典歌曲'
      },
      {
        id: 4,
        name: '轻音乐',
        cover: 'https://picsum.photos/300/300?random=4',
        songCount: 15,
        description: '放松心情的轻音乐'
      }
    ];
    
    // 初始化编辑资料数据
    const editProfile = {
      nickname: userInfo.nickname || '',
      bio: userInfo.bio || '',
      avatar: userInfo.avatar || ''
    };
    
    this.setData({
      userInfo,
      playHistory: playHistory.slice(0, 10), // 显示最近10条记录
      favorites: favorites.slice(0, 20), // 显示最多20条收藏
      recommendedPlaylists,
      editProfile,
      localMusic: [] // 本地音乐列表
    });
  },

  updateData() {
    // 从本地存储更新数据
    const playHistory = app.getHistory();
    const favorites = app.getFavorites();
    
    this.setData({
      playHistory: playHistory.slice(0, 10),
      favorites: favorites.slice(0, 20)
    });
  },

  // 菜单功能 - 使用真实数据
  viewFavorites() {
    const favorites = app.getFavorites();
    if (favorites.length === 0) {
      wx.showToast({
        title: '暂无收藏歌曲',
        icon: 'none'
      });
      return;
    }
    
    this.setData({
      showFavoritesModal: true,
      favorites: favorites
    });
  },

  viewPlayHistory() {
    const history = app.getHistory();
    if (history.length === 0) {
      wx.showToast({
        title: '暂无播放历史',
        icon: 'none'
      });
      return;
    }
    
    wx.navigateTo({
      url: '/pages/history/history'
    });
  },

  // 用户操作
  editProfile() {
    this.setData({
      showEditProfileModal: true
    });
  },

  shareProfile() {
    wx.showToast({
      title: '分享功能开发中',
      icon: 'none'
    });
  },

  // 统计数据点击
  viewFavorites() {
    this.setData({
      showFavoritesModal: true
    });
  },

  viewPlayHistory() {
    const history = app.getHistory();
    if (history.length === 0) {
      wx.showToast({
        title: '暂无播放历史',
        icon: 'none'
      });
      return;
    }
    
    wx.navigateTo({
      url: '/pages/history/history'
    });
  },

  viewFollowing() {
    wx.showToast({
      title: '查看关注列表开发中',
      icon: 'none'
    });
  },

  // 推荐歌单操作
  viewPlaylist(e) {
    const playlist = e.currentTarget.dataset.playlist;
    if (playlist) {
      wx.showToast({
        title: `打开歌单: ${playlist.name}`,
        icon: 'success'
      });
      
      // 这里可以跳转到歌单详情页面
      // wx.navigateTo({
      //   url: `/pages/playlist/playlist?id=${playlist.id}`
      // });
    }
  },

  viewAllPlaylists() {
    wx.showToast({
      title: '查看所有推荐歌单',
      icon: 'none'
    });
    
    // 这里可以跳转到歌单列表页面
    // wx.navigateTo({
    //   url: '/pages/playlists/playlists'
    // });
  },

  // 最近播放操作
  playRecentSong(e) {
    const song = e.currentTarget.dataset.song;
    if (song) {
      // 播放歌曲
      app.playSong(song);
      
      wx.showToast({
        title: `播放: ${song.name}`,
        icon: 'success'
      });
      
      // 返回首页
      wx.switchTab({
        url: '/pages/index/index'
      });
    }
  },

  viewAllHistory() {
    wx.showToast({
      title: '查看所有播放历史',
      icon: 'none'
    });
  },

  // 收藏功能
  playFavorite(e) {
    const song = e.currentTarget.dataset.song;
    if (song) {
      // 播放收藏的歌曲
      app.playSong(song);
      
      wx.showToast({
        title: `播放: ${song.name}`,
        icon: 'success'
      });
      
      // 返回首页
      wx.switchTab({
        url: '/pages/index/index'
      });
    }
  },

  removeFavorite(e) {
    const songId = e.currentTarget.dataset.id;
    if (songId) {
      // 从收藏列表中移除
      const newFavorites = this.data.favorites.filter(item => item.id !== songId);
      this.setData({
        favorites: newFavorites
      });
      
      wx.showToast({
        title: '已取消收藏',
        icon: 'success'
      });
    }
  },

  closeFavoritesModal() {
    this.setData({
      showFavoritesModal: false
    });
  },

  // 时间格式化函数
  formatTime(timestamp) {
    if (!timestamp) return '';
    
    const now = Date.now();
    const diff = now - timestamp;
    const minute = 60 * 1000;
    const hour = 60 * minute;
    const day = 24 * hour;
    
    if (diff < minute) {
      return '刚刚';
    } else if (diff < hour) {
      return Math.floor(diff / minute) + '分钟前';
    } else if (diff < day) {
      return Math.floor(diff / hour) + '小时前';
    } else if (diff < 7 * day) {
      return Math.floor(diff / day) + '天前';
    } else {
      const date = new Date(timestamp);
      return `${date.getMonth() + 1}月${date.getDate()}日`;
    }
  },

  // 页面跳转功能
  onBack() {
    wx.navigateBack();
  },

  // 查看所有收藏
  viewAllFavorites() {
    wx.navigateTo({
      url: '/pages/favorites/favorites'
    });
  },

  // 查看所有历史
  viewAllHistory() {
    wx.navigateTo({
      url: '/pages/history/history'
    });
  },

  // 分享功能
  onShareAppMessage() {
    return {
      title: '我的音乐主页',
      path: '/pages/profile/profile'
    };
  },

  // 本地音乐弹窗功能
  viewLocalMusic() {
    this.setData({
      showLocalMusicModal: true
    });
  },

  closeLocalMusicModal() {
    this.setData({
      showLocalMusicModal: false
    });
  },

  playLocalMusic(e) {
    const song = e.currentTarget.dataset.song;
    if (song) {
      app.playSong(song);
      wx.showToast({
        title: `播放: ${song.name}`,
        icon: 'success'
      });
      wx.switchTab({
        url: '/pages/index/index'
      });
    }
  },

  deleteLocalMusic(e) {
    const songId = e.currentTarget.dataset.id;
    const newLocalMusic = this.data.localMusic.filter(item => item.id !== songId);
    this.setData({
      localMusic: newLocalMusic
    });
    wx.showToast({
      title: '已删除本地音乐',
      icon: 'success'
    });
  },

  addLocalMusic() {
    wx.showToast({
      title: '请选择本地音乐文件',
      icon: 'none'
    });
  },

  formatDuration(duration) {
    if (!duration) return '00:00';
    const minutes = Math.floor(duration / 60);
    const seconds = Math.floor(duration % 60);
    return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
  },

  // 设置弹窗功能
  viewSettings() {
    this.setData({
      showSettingsModal: true
    });
  },

  closeSettingsModal() {
    this.setData({
      showSettingsModal: false
    });
  },

  onQualityChange(e) {
    this.setData({
      qualityIndex: parseInt(e.detail.value)
    });
    wx.showToast({
      title: `音质已切换为: ${this.data.qualityOptions[this.data.qualityIndex]}`,
      icon: 'success'
    });
  },

  onAutoPlayChange(e) {
    this.setData({
      autoPlay: e.detail.value
    });
    wx.showToast({
      title: `自动播放: ${e.detail.value ? '开启' : '关闭'}`,
      icon: 'success'
    });
  },

  clearCache() {
    wx.showModal({
      title: '清理缓存',
      content: '确定要清理所有缓存数据吗？',
      success: (res) => {
        if (res.confirm) {
          wx.clearStorage();
          wx.showToast({
            title: '缓存已清理',
            icon: 'success'
          });
        }
      }
    });
  },

  viewAbout() {
    wx.showModal({
      title: '关于我们',
      content: '音乐播放器 v1.0.0\
\
一款简洁易用的音乐播放小程序',
      showCancel: false
    });
  },

  // 编辑资料弹窗功能
  editProfile() {
    this.setData({
      showEditProfileModal: true
    });
  },

  closeEditProfileModal() {
    this.setData({
      showEditProfileModal: false
    });
  },

  onNicknameChange(e) {
    const editProfile = {...this.data.editProfile, nickname: e.detail.value};
    this.setData({ editProfile });
  },

  onBioChange(e) {
    const editProfile = {...this.data.editProfile, bio: e.detail.value};
    this.setData({ editProfile });
  },

  chooseAvatar() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const editProfile = {...this.data.editProfile, avatar: res.tempFiles[0].tempFilePath};
        this.setData({ editProfile });
        wx.showToast({
          title: '头像已选择',
          icon: 'success'
        });
      }
    });
  },

  saveProfile() {
    const { editProfile } = this.data;
    if (!editProfile.nickname.trim()) {
      wx.showToast({
        title: '请输入昵称',
        icon: 'none'
      });
      return;
    }

    this.setData({
      userInfo: {...this.data.userInfo, ...editProfile}
    });

    wx.showToast({
      title: '资料保存成功',
      icon: 'success'
    });

    this.closeEditProfileModal();
  }
});